package com.fast.common.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SysLogAspect {

	private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");
	
	@Autowired
	private SysLogHandler log ;
	
	public static long getStartTimeThreadLocal(){
		return startTimeThreadLocal.get() ;
	}

	/**
	 * 切入点
	 */
	@Pointcut("@annotation(com.fast.common.annotation.Log)")
	public void pointcutAspect() {}

	@Before("pointcutAspect()")
	public void doBefor(JoinPoint joinPoint) {
		long beginTime = System.currentTimeMillis();// 1、开始时间
		startTimeThreadLocal.set(beginTime); // 线程绑定变量（该数据只有当前请求的线程可见）
	}

	@Around("pointcutAspect()")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		Object proceed = joinPoint.proceed();
		this.log.saveAccessLog(joinPoint);
		return proceed;
	}
	
	@AfterThrowing(pointcut = "pointcutAspect()", throwing = "ex")
	public void doAfterThrowing(JoinPoint joinPoint, Throwable ex) {
		this.log.saveErrorLog(joinPoint, ex);
	}
}
